package io.hei.modules.kbms.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.hei.common.utils.PageUtils;
import io.hei.common.utils.Query;
import io.hei.modules.kbms.dao.KbmsFileClassifyDao;
import io.hei.modules.kbms.entity.KbmsFileClassifyEntity;
import io.hei.modules.kbms.service.KbmsFileClassifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


@Service("kbmsFileClassifyService")
public class KbmsFileClassifyServiceImpl extends ServiceImpl<KbmsFileClassifyDao, KbmsFileClassifyEntity> implements KbmsFileClassifyService {

    @Autowired
    KbmsFileClassifyDao kbmsFileClassifyDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<KbmsFileClassifyEntity> page = this.page(
                new Query<KbmsFileClassifyEntity>().getPage(params),
                new QueryWrapper<KbmsFileClassifyEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<KbmsFileClassifyEntity> selectAll(){

        return kbmsFileClassifyDao.selectAll();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Map<String, Object> params) {

        KbmsFileClassifyEntity kbmsFileClassify = new KbmsFileClassifyEntity();

        /**
         * 保存父级目录
         */
        if("".equals(params.get("parent")) || params.get("parent") == null){
            kbmsFileClassify.setWeight(5);
            kbmsFileClassify.setParentId(0);
            kbmsFileClassify.setName((String) params.get("label"));

            kbmsFileClassifyDao.insert(kbmsFileClassify);

            return;
        }

        /**
         * 保存子级目录
         */
        JSON parent = JSONUtil.parse(params.get("parent"));
        kbmsFileClassify.setWeight(5);
        kbmsFileClassify.setParentId(Integer.parseInt((String) parent.getByPath("id")));
        kbmsFileClassify.setName((String) params.get("label"));
        kbmsFileClassifyDao.insert(kbmsFileClassify);
    }

}
